package com.ndood.admin.core.security.handler;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.NullRequestCache;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ndood.core.properties.CommonConstants;
import com.ndood.core.support.SimpleResponse;

/**
 * 添加认证成功处理类，将日志插入数据库
 * @author ndood
 */
@Component("adminAuthenticationSuccessHandler")
public class AdminAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler{
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	//@Autowired
	private ObjectMapper objectMapper = new ObjectMapper();
	
	/*@Autowired
	private SecurityProperties securityProperties;*/
	
	/**
	 * 认证成功处理
	 */
	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
			throws IOException, ServletException {
		logger.info("登录成功");
		// 根据配置进行处理
		/*if(LoginResponseType.JSON.equals(securityProperties.getBrowser().getSignInResponseType())){
			response.setContentType("application/json;charset=UTF-8");
			response.getWriter().write(objectMapper.writeValueAsString(new SimpleResponse(CommonConstants.SUCCESS,"登录成功")));
			response.getWriter().flush();
		} else{
			super.onAuthenticationSuccess(request, response, authentication);
		}*/
		if(isJson(request)|isAjax(request)) {
			response.setContentType("application/json;charset=UTF-8");
			response.getWriter().write(objectMapper.writeValueAsString(new SimpleResponse(CommonConstants.SUCCESS,"登录成功")));
			response.getWriter().flush();
			return;
		}
		// 单页应用不需要登录会跳到原来的地址，便于社交登录处理
		super.setRequestCache(new NullRequestCache());
		super.onAuthenticationSuccess(request, response, authentication);
	}
	
	/**
	 * 判断是否是json请求
	 */
	public Boolean isJson(HttpServletRequest request) {
		boolean isJson = request.getHeader("content-type") != null
				&& request.getHeader("content-type").contains("json");
		return isJson;
	}

	/**
	 * 判断是否是ajax请求
	 */
	public static boolean isAjax(HttpServletRequest httpRequest) {
		boolean isAjax = httpRequest.getHeader("X-Requested-With") != null
				&& "XMLHttpRequest".equals(httpRequest.getHeader("X-Requested-With").toString());
		return isAjax;
	}
}